package com.abigdreamer.wordpress.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;

import com.abigdreamer.wordpress.newspider.HtmlSpider;

/**   
 * 
 * @author Darkness
 * @date 2013-6-29 下午10:45:15 
 * @version V1.0   
 */
public class HttpImageGetter {
	
	static HtmlSpider htmlSpider = new HtmlSpider();
	
	public static void file_put_contents(String file_name, String urlstr) {

		if(urlstr == null){
			return ;
		}
		HttpGet get = new HttpGet(urlstr);
		String[] strs = urlstr.split("/");
		String fileName = strs[strs.length-1];
	    String savePath = file_name;//IMGPATH+File.separator+fileName;
	    if (new File(savePath).exists()) {
			return;
		}
		HttpEntity entity = null;
		try {
			HttpResponse response = null;
			try {
				htmlSpider.getclient().execute(get);
			} catch (Exception e) {
				htmlSpider = new HtmlSpider();
				htmlSpider.getclient().execute(get);
			}
			
			entity = response.getEntity();
			//System.out.println("保存图片>>>>.>>>>>>"+fileName);
			InputStream is = entity.getContent();
			OutputStream os = new FileOutputStream(savePath);
			IOUtils.copy(is, os);
			IOUtils.closeQuietly(os);
			IOUtils.closeQuietly(is);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("图片保存失败");
			return ;
		}
		
	}
}
